<?php

namespace common\biz;

use peng\enums\DBOperator;

/**
 * 业务逻辑层-用户信息
 *
 * @author peng.huang
 */
class UserInfoBiz extends \common\base\BaseBiz {

    /**
     * 构造函数
     */
    public function __construct() {
        $this->dao = static::getDao('common\dao\UserInfoDao');
    }

    /**
     * 查询一条数据
     * 
     * @param string $fields [字段]
     * @param object $entity [实体对象]
     * @return array
     */
    public function findOne($fields, $entity) {
        return $this->dao->findOne($fields, array('userid' => $entity->userid));
    }

    /**
     * 查询数据
     * 
     * @param string $fields [字段]
     * @param object $entity [实体对象]
     * @param boolean $checkUserToken [验证账号和令牌]
     * @return array
     */
    public function find($fields, $entity, $checkUserToken = FALSE) {
        if (!$entity->validate()) {
            return FALSE;
        }

        // 验证账号和令牌
        if ($checkUserToken && !$this->isUserTokenValid($entity)) {
            return FALSE;
        }

        return $this->findOne($fields, $entity);
    }

    /**
     * 保存数据
     * 
     * @param object $entity [实体对象]
     * @param boolean $checkUserToken [验证账号和令牌]
     * @return bool
     */
    public function save($entity, $checkUserToken = FALSE) {
        if (!$entity->validate()) {
            return FALSE;
        }

        // 验证账号和令牌
        if ($checkUserToken && !$this->isUserTokenValid($entity)) {
            return FALSE;
        }

        // 用户信息只允许一条
        $row = $this->dao->findOne('id', array('userid' => $entity->userid));
        if (!empty($row)) {
            $entity->id = $row['id'];
            $entity->operator = DBOperator::UPDATE;
        } else {
            $entity->operator = DBOperator::INSERT;
        }

        $data = $this->getSavedData($entity);
        return -1 < $this->dao->save($data);
    }

}
